class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}

public class LeetCode {
    public ListNode reverseKGroup(ListNode head, int k) {
        //求出链表长度
        int n = 0;
        ListNode cou = head;
        while(cou!=null){
            n++;
            cou = cou.next;
        }
        //求出需要逆转几次
        n/=k;
        ListNode newhead = new ListNode(0);
        ListNode prev = newhead;
        ListNode cur = head;
        for (int i = 0; i < n; i++) {
            ListNode tmp = cur;
            for (int j = 0; j < k; j++) {
                ListNode next = cur.next;
                cur.next = prev.next;
                prev.next = cur;
                cur = next;
            }
            prev = tmp;
        }
        prev.next = cur;
        return newhead.next;
    }
}
